﻿#include "USceneManager.h"
#include <QMenu>
#include <QDir>
#include <QDebug>
#include "UToolBarManager.h"
#include "Global.h"
#include "CBaseNode.h"
USceneManager::USceneManager(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	// 注册元类型
	qRegisterMetaType<SPageItem>("SPageItem");
	qRegisterMetaType<QVector<SPageItem>>("QVector<SPageItem>");
	g_pRootScene = NULL;
	m_pNodeCurr = nullptr;
}

USceneManager::~USceneManager()
{}

void USceneManager::setDropCellWidget(UDropCellWidget * pWidget)
{
	m_pDropWidget = pWidget;
}

void USceneManager::addNode(CBaseScene * parent)
{
	if (parent == NULL)
	{
		parent = g_pRootScene;
	}
	QString sNodeName ="#" + QString::number(parent->getChildren().size()+1) + A2T("节点");
	QString sStr = showGetText(this, A2T("添加节点"), A2T("请输入节点名称"), sNodeName);
	if (!sStr.isEmpty())
	{
		CNodeScene* node = new CNodeScene(sStr, parent);
		m_pNodeCurr = node;
		showContextLeft(m_pNodeCurr);
		refushMenu();
	}
}

void USceneManager::addPage(CBaseScene * parent)
{
	if (parent == NULL)
	{
		parent = g_pRootScene;
	}
	QString sNodeName ="#" + QString::number(parent->getChildren().size() + 1) + A2T("组合场景");
	QString sStr = showGetText(this, A2T("添加组合场景"), A2T("请输入组合场景名称"),sNodeName);
	if (!sStr.isEmpty())
	{		
		QVector<SPageItem>vecPageItem;
		m_pDropWidget->setGridItems(vecPageItem);
		CPageScene* node = new CPageScene(sStr, parent);
		m_pNodeCurr = node;
		showContextLeft(m_pNodeCurr);
		refushMenu();
	}
}

void USceneManager::deleteNode(CBaseScene * node)
{
	if (node == nullptr)
	{
		showMessageBox(this, A2T("警告"), A2T("请先选择节点或界面"), 1);
		return;
	}
	if (node == g_pRootScene)
	{
		showMessageBox(this, A2T("警告"), A2T("根节点不允许删除"), 1);
		return;
	}
	bool bSure = showMessageBox(this, A2T("提示"), A2T("确认删除此节点或者界面吗？"), 1, true);
	if (bSure)
	{
		int index = node->getParent()->getChildren().indexOf(node);
		node->getParent()->removeChild(node);
	}
}

void USceneManager::showPage(CBaseScene * node)
{
	CPageScene *pPage = (CPageScene *)node;
	m_pDropWidget->setGridItems(pPage->getPageItems());
}

void USceneManager::initUi()
{
	ui.treeView->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui.treeView->setSelectionMode(QAbstractItemView::SingleSelection);
	ui.treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);  // 禁用编辑
	//ui.treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); // 支持 Ctrl 和 Shift 多选
	ui.treeView->header()->hide();
	model = new CPageModel(this);
	//model->setHorizontalHeaderLabels(QStringList() << A2T("煤场管理"));
	ui.treeView->setModel(model);
	ui.treeView->setContextMenuPolicy(Qt::CustomContextMenu);
	ui.treeView->viewport()->installEventFilter(this);
	ui.treeView->setDragEnabled(true);
	ui.toolButton->setIcon(QIcon(":/SmartControl/Resource/toolbar/add_2.png"));
	ui.toolButton_4->setIcon(QIcon(":/SmartControl/Resource/toolbar/adddevice_2.png"));
	ui.toolButton_2->setIcon(QIcon(":/SmartControl/Resource/toolbar/delete_2.png"));
	ui.toolButton->setIconSize(QSize(30, 30));
	ui.toolButton_4->setIconSize(QSize(30, 30));
	ui.toolButton_2->setIconSize(QSize(30, 30));
	ui.toolButton->setToolButtonStyle(Qt::ToolButtonIconOnly);
	ui.toolButton_4->setToolButtonStyle(Qt::ToolButtonIconOnly);
	ui.toolButton_2->setToolButtonStyle(Qt::ToolButtonIconOnly);
	connect(ui.toolButton, SIGNAL(clicked()), this, SLOT(slot_addNode()));
	connect(ui.toolButton_4, SIGNAL(clicked()), this, SLOT(slot_addPage()));
	connect(ui.toolButton_2, SIGNAL(clicked()), this, SLOT(slot_deleteNode()));
	connectTree();
	QString exePath = QCoreApplication::applicationDirPath();
	// 构建配置文件的完整路径
	QString configFilePath = QDir(exePath).filePath("scene.xml");
	QAction *pAdd = g_pToolBarMang->addAction(UToolBarManager::Scene, A2T("添加节点"), QIcon(":/SmartControl/Resource/toolbar/add.png"));
	QAction *pAddDevice= g_pToolBarMang->addAction(UToolBarManager::Scene, A2T("添加场景"), QIcon(":/SmartControl/Resource/toolbar/adddevice.png"));
	QAction *pDelete=g_pToolBarMang->addAction(UToolBarManager::Scene, A2T("删除"), QIcon(":/SmartControl/Resource/toolbar/delete.png"));
	g_pToolBarMang->addSeparator(UToolBarManager::Scene);
	connect(pAdd, &QAction::triggered, this, &USceneManager::slot_addNode);
	connect(pAddDevice, &QAction::triggered, this, &USceneManager::slot_addPage);
	connect(pDelete, &QAction::triggered, this, &USceneManager::slot_deleteNode);
}

void USceneManager::refushUi()
{
	model->removeRow(0);
	model->appendRow(g_pRootScene->getItem());
	QModelIndex index = g_pRootScene->getItem()->index(); // 获取该 item 对应的 QModelIndex
	ui.treeView->expand(index);
	m_pNodeCurr = g_pRootScene;
}

void USceneManager::showContextMenu(CBaseScene * node, const QPoint & globalPos)
{
	QMenu* menu = new QMenu(this);

	// 通用菜单
	menu->addAction(A2T("重命名"), this, [this, node]() { renameNode(node); });

	// 删除操作
	switch (node->getType()) {
	case CBaseScene::enRootScene:
		menu->addAction(QIcon(":/SmartControl/Resource/toolbar/add.png"), A2T("添加节点(N)..."), this, [=]() { addNode(node); });
		menu->addAction(QIcon(":/SmartControl/Resource/toolbar/adddevice.png"), A2T("添加场景(P)..."), this, [=]() {addPage(node); });
		break;
	case CBaseScene::enNodeScene:
		menu->addAction(QIcon(":/SmartControl/Resource/toolbar/add.png"), A2T("添加节点(N)..."), this, [=]() { addNode(node); });
		menu->addAction(QIcon(":/SmartControl/Resource/toolbar/adddevice.png"), A2T("添加场景(P)..."), this, [=]() {addPage(node); });
		menu->addAction(A2T("删除节点(D)"), this, [=]() { slot_deleteNode(); });
		break;
	case CBaseScene::enPageScene:
		menu->addAction(A2T("删除组合场景(D)"), this, [=]() { slot_deleteNode(); });
		break;
	default:
		break;
	}
	menu->exec(globalPos);
	delete menu;
}

void USceneManager::showContextLeft(CBaseScene * node)
{
	//if (m_pNodeCurr == node)
	//{
	//	return;
	//}
	updateCurrPage();
	switch (node->getType())
	{
	case CBaseScene::enRootScene:
		m_pNodeCurr = node;
		m_pDropWidget->setVisible(false);
		break;
	case CBaseScene::enNodeScene:
		m_pNodeCurr = node;
		m_pDropWidget->setVisible(false);
		break;
	case CBaseScene::enPageScene:
		m_pDropWidget->setVisible(true);
		showPage(node);
		m_pNodeCurr = node;
		break;
	default:
		m_pNodeCurr = node;
		break;
	}
}

void USceneManager::connectTree()
{
	ui.treeView->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(ui.treeView, &QTreeView::customContextMenuRequested, this, &USceneManager::onTreeContextMenuRequested);
}

void USceneManager::createNullMenu(const QPoint& globalPos)
{
	QMenu* menu = new QMenu(this);

	if (m_pNodeCurr == nullptr)
	{
		m_pNodeCurr = g_pRootScene;
	}
	CBaseScene* node = m_pNodeCurr;
	if (m_pNodeCurr->getType() == CBaseScene::enPageScene)
	{
		node = (CBaseScene*)m_pNodeCurr->getParent();
	}
	menu->addAction(QIcon(":/SmartControl/Resource/toolbar/add.png"), A2T("添加节点(N)..."), this, [=]() { addNode(node); });
	menu->addAction(QIcon(":/SmartControl/Resource/toolbar/adddevice.png"), A2T("添加场景(P)..."), this, [=]() {addPage(node); });
	menu->exec(globalPos);
	delete menu;

}
void USceneManager::createRootMenu(QMenu * menu, CBaseScene * node)
{
}

void USceneManager::createNodeMenu(QMenu * menu, CBaseScene * node)
{
}

void USceneManager::createPageMenu(QMenu * menu, CBaseScene * node)
{
}

void USceneManager::updateCurrPage()
{
	if (m_pNodeCurr != nullptr)
	{
		if (m_pNodeCurr->getType() == CBaseScene::enPageScene)
		{
			CPageScene *pPage = (CPageScene *)m_pNodeCurr;
			QVector<SPageItem>vecPageItem = m_pDropWidget->getGridItems();
			pPage->setPageItems(vecPageItem);
		}
	}
}

bool USceneManager::eventFilter(QObject * obj, QEvent * event)
{
	if (obj == ui.treeView->viewport() && event->type() == QEvent::MouseButtonPress)
	{
		QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);

		if (mouseEvent->button() == Qt::LeftButton)
		{
			onTreeLeftClieck(mouseEvent->pos());
		}
	}

	return QObject::eventFilter(obj, event); // 交给默认处理
}

void USceneManager::onTreeLeftClieck(const QPoint & pos)
{
	emit sign_Show(0);
	QModelIndex index = ui.treeView->indexAt(pos);
	if (!index.isValid())
	{
		refushMenu();
		return;
	}

	QStandardItem* item = model->itemFromIndex(index);
	if (!item)
	{
		refushMenu();
		return;
	}

	CBaseScene* node = reinterpret_cast<CBaseScene*>(item->data(Qt::UserRole).value<void*>());
	if (!node) 
	{
		refushMenu();
		return;
	}
	showContextLeft(node);
	refushMenu();
}

void USceneManager::renameNode(CBaseScene * node)
{
	if (!node) return;

	QStandardItem* item = node->getItem();
	if (!item) return;

	// 允许临时编辑
	ui.treeView->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed);

	QModelIndex index = item->index();
	ui.treeView->edit(index);
	// 防止多次连接 itemChanged（避免重复触发）
	static QMetaObject::Connection conn;
	if (conn) QObject::disconnect(conn);
	// 监听编辑完成后恢复禁止编辑
	conn = connect(model, &QStandardItemModel::itemChanged, this, [=](QStandardItem* changedItem)
	{
		if (changedItem == item)
		{
			node->setName(item->text());  // 同步修改到 node
			QString newName = item->text();
			ui.treeView->setEditTriggers(QAbstractItemView::NoEditTriggers); // 编辑完成后再次禁用
			QObject::disconnect(conn); // 编辑完后断开连接

		}
	});
}

void USceneManager::slot_addNode()
{
	if (m_pNodeCurr == NULL)
	{
		m_pNodeCurr = g_pRootScene;
	}
	if (m_pNodeCurr->getType() != CBaseScene::enPageScene)
	{
		addNode(m_pNodeCurr);
	}
	else
	{
		showMessageBox(this, A2T("警告"), A2T("请选择一个节点"), 1);
	}
}

void USceneManager::slot_addPage()
{
	if (m_pNodeCurr == NULL)
	{
		m_pNodeCurr = g_pRootScene;
	}
	if (m_pNodeCurr->getType() != CBaseScene::enPageScene)
	{
		addPage(m_pNodeCurr);
	}
	else
	{
		showMessageBox(this, A2T("警告"), A2T("请选择一个节点"), 1);
	}
}

void USceneManager::slot_deleteNode()
{
	if (m_pNodeCurr == nullptr)
	{
		showMessageBox(this, A2T("警告"), A2T("请先选择节点或界面"), 1);
		return;
	}
	if (m_pNodeCurr == g_pRootScene)
	{
		showMessageBox(this, A2T("警告"), A2T("根节点不允许删除"), 1);
		return;
	}
	bool bSure = showMessageBox(this, A2T("提示"), A2T("确认删除此节点或者界面吗？"), 1, true);
	if (bSure)
	{
		CBase* pParrent = m_pNodeCurr->getParent();
		int index = pParrent->getChildren().indexOf(m_pNodeCurr);
		pParrent->removeChild(m_pNodeCurr);
		m_pNodeCurr = (CBaseScene*)pParrent;
		refushMenu();
	}
}

void USceneManager::onTreeContextMenuRequested(const QPoint & pos)
{
	emit sign_Show(0);
	QModelIndex index = ui.treeView->indexAt(pos);
	if (!index.isValid())
	{
		refushMenu();
		createNullMenu(ui.treeView->viewport()->mapToGlobal(pos));
		return;
	}

	QStandardItem* item = model->itemFromIndex(index);
	if (!item) return;

	CBaseScene* node = reinterpret_cast<CBaseScene*>(item->data(Qt::UserRole).value<void*>());
	if (!node) return;
	m_pNodeCurr = node;
	showContextMenu(node, ui.treeView->viewport()->mapToGlobal(pos));
	refushMenu();
}


void USceneManager::refushMenu()
{
	if (m_pNodeCurr == nullptr)
	{
		m_pNodeCurr = g_pRootScene;
	}
	m_pNodeCurr->showItem(ui.treeView);
	if (m_pNodeCurr->getType() == CBaseScene::enRootScene)
	{
		g_pToolBarMang->setToolBtn(UToolBarManager::Scene, 1);
	}
	else
	{
		g_pToolBarMang->setToolBtn(UToolBarManager::Scene, 0);
	}
}